<template>
  <div class="rooms">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>房间管理</span>
          <div class="header-actions">
            <el-button @click="refreshRooms" :loading="loading">
              刷新
            </el-button>
            <el-button type="primary" @click="showAddModal = true">
              新增房间
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索房间号..."
          style="width: 200px; margin-right: 12px;"
          clearable
        ></el-input>
        <el-select v-model="buildingFilter" placeholder="楼栋" style="width: 150px; margin-right: 12px;" clearable>
          <el-option v-for="b in buildings" :key="b.id" :label="b.name" :value="b.id" />
        </el-select>
        <el-select v-model="roomStatusFilter" placeholder="房间状态" style="width: 120px; margin-right: 12px;" clearable>
          <el-option label="空闲" :value="0" />
          <el-option label="已住满" :value="1" />
          <el-option label="维修中" :value="2" />
        </el-select>
        <el-select v-model="enableStatusFilter" placeholder="启用状态" style="width: 120px; margin-right: 12px;" clearable>
          <el-option label="禁用" :value="0" />
          <el-option label="启用" :value="1" />
        </el-select>
        <el-select v-model="mixStatusFilter" placeholder="混合寝室" style="width: 120px; margin-right: 12px;" clearable>
          <el-option label="否" :value="0" />
          <el-option label="是" :value="1" />
        </el-select>
        <el-select v-model="professionFilter" placeholder="专业" style="width: 150px; margin-right: 12px;" clearable>
          <el-option v-for="pro in professions" :key="pro.id" :label="pro.name" :value="pro.id" />
        </el-select>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>

      <el-table :data="rooms" style="width: 100%" v-loading="loading">
        <el-table-column label="房间信息" min-width="200">
          <template #default="{ row }">
            <div class="room-info">
              <div class="room-number">{{ row.roomNumber }}</div>
              <div class="room-desc">{{ row.des || '暂无描述' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="楼栋" width="100">
          <template #default="{ row }">
            <span class="building-name">{{ getBuildingName(row.buildingId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="床位数" width="100">
          <template #default="{ row }">
            <div class="bed-count">
              <span class="count">{{ row.count }}</span>
              <span class="label">张</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="房间状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoomStatusTagType(row.roomStatus)">
              {{ getRoomStatusText(row.roomStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getEnableStatusTagType(row.status)">
              {{ getEnableStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="混合寝室" width="100">
          <template #default="{ row }">
            <el-tag :type="getMixStatusTagType(row.isMix)">
              {{ getMixStatusText(row.isMix) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="专业" min-width="120">
          <template #default="{ row }">
            <span>{{ getProfessionName(row.professionId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="right">
          <template #default="{ row }">
            <el-button 
              type="warning" 
              size="small" 
              @click="editRoom(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="manageBeds(row)"
            >
              床位
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="deleteRoom(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRooms"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑房间对话框 -->
    <el-dialog :model-value="showModal" :title="modalTitle" width="600px" @close="closeModal">
      <el-form :model="roomForm" label-width="80px">
        <el-form-item label="房间号">
          <el-input 
            v-model="roomForm.roomNumber"
            placeholder="如：101"
          />
        </el-form-item>
        <el-form-item label="楼栋">
          <el-select v-model="roomForm.buildingId" placeholder="选择楼栋" style="width: 100%;">
            <el-option 
              v-for="building in buildings" 
              :key="building.id" 
              :label="building.name" 
              :value="building.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="床位数">
          <el-input-number 
            v-model="roomForm.count"
            :min="1"
            :max="8"
            placeholder="床位数"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="房间描述">
          <el-input 
            v-model="roomForm.des"
            type="textarea"
            placeholder="房间描述信息..."
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="房间状态">
          <el-select v-model="roomForm.roomStatus" placeholder="选择房间状态" style="width: 100%;">
            <el-option label="空闲" :value="0" />
            <el-option label="已住满" :value="1" />
            <el-option label="维修中" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="roomForm.status" placeholder="选择启用状态" style="width: 100%;">
            <el-option label="禁用" :value="0" />
            <el-option label="启用" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否混合寝室">
          <el-select v-model="roomForm.isMix" placeholder="选择是否混合寝室" style="width: 100%;">
            <el-option label="否" :value="0" />
            <el-option label="是" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="roomForm.professionId" placeholder="请选择专业">
            <el-option v-for="pro in professions" :key="pro.id" :label="pro.name" :value="pro.id" />
          </el-select>
        </el-form-item>
        
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeModal">取消</el-button>
          <el-button type="primary" @click="saveRoom">
            {{ showAddModal ? '新增' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryRoomAPI, addRoomAPI, updateRoomAPI, deleteRoomAPI } from '@/apis/roomAPI'
import { queryDormBuild } from '@/apis/roomBuildAPI'
import { queryProfessionAPI } from '@/apis/professionAPI'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const roomStatusFilter = ref('')
const enableStatusFilter = ref('')
const mixStatusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const showAddModal = ref(false)
const showEditModal = ref(false)
const editingRoom = ref(null)
const buildingFilter = ref('')
const professionFilter = ref('')

// 房间表单
const roomForm = ref({
  roomNumber: '',
  buildingId: '',
  count: 4,
  des: '',
  professionId: '', // 用 professionId
  roomStatus: 0,
  status: 1,
  isMix: 0,
})

// 数据
const buildings = ref([])
const rooms = ref([])
const totalRooms = ref(0)
const professions = ref([])

const showModal = computed(() => showAddModal.value || showEditModal.value)
const modalTitle = computed(() => showAddModal.value ? '新增房间' : '编辑房间')

// 方法
const getBuildingName = (buildingId) => {
  const building = buildings.value.find(b => b.id === buildingId)
  return building ? building.name : '未知楼栋'
}

// 房间状态相关函数
const getRoomStatusText = (status) => {
  const statusMap = {
    0: '空闲',
    1: '已住满',
    2: '维修中'
  }
  return statusMap[status] || '未知状态'
}

const getRoomStatusTagType = (status) => {
  const typeMap = {
    0: 'success',
    1: 'danger',
    2: 'warning'
  }
  return typeMap[status] || 'info'
}

// 启用状态相关函数
const getEnableStatusText = (status) => {
  const statusMap = {
    0: '禁用',
    1: '启用'
  }
  return statusMap[status] || '未知状态'
}

const getEnableStatusTagType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'success'
  }
  return typeMap[status] || 'info'
}
// 混合寝室相关函数
const getMixStatusText = (isMix) => {
  const statusMap = {
    0: '否',
    1: '是'
  }
  return statusMap[isMix] || '未知'
}
const getMixStatusTagType = (isMix) => {
  const typeMap = {
    0: 'info',
    1: 'warning'
  }
  return typeMap[isMix] || 'info'
}

// 获取专业展示名
const getProfessionName = (id) => {
  const pro = professions.value.find(i => i.id === id)
  return pro ? pro.name : '—'
}

// 分页查询（接口）
const fetchRooms = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      roomNumber: searchQuery.value || undefined,
      buildingId: buildingFilter.value !== '' ? buildingFilter.value : undefined,
      roomStatus: roomStatusFilter.value !== '' ? roomStatusFilter.value : undefined,
      status: enableStatusFilter.value !== '' ? enableStatusFilter.value : undefined,
      isMix: mixStatusFilter.value !== '' ? mixStatusFilter.value : undefined,
      professionId: professionFilter.value !== '' ? professionFilter.value : undefined,
    }
    const res = await queryRoomAPI(params)
    if (res && res.code === 0 && res.data) {
      rooms.value = res.data.records || []
      totalRooms.value = res.data.total || 0
    } else {
      rooms.value = []
      totalRooms.value = 0
      ElMessage.error(res.msg || '获取房间数据失败')
    }
  } catch (error) {
    rooms.value = []
    totalRooms.value = 0
    ElMessage.error('获取房间数据异常')
  } finally {
    loading.value = false
  }
}
// 刷新/重载
const refreshRooms = async () => {
  await fetchRooms()
  ElMessage.success('数据刷新成功')
}
// 楼栋数据原逻辑不变
const refreshBuildings = async () => {
  try {
    const res = await queryDormBuild()
    if (res && res.code === 0) {
      buildings.value = res.data || []
    } else {
      ElMessage.error(res.msg || '获取楼栋数据失败')
    }
  } catch (error) {
    console.error('获取楼栋数据失败:', error)
  }
}

// 其它事件如查看、编辑、管理床位、保存、关闭对话框、删除房间等不变，只刷新用 fetchRooms 即可
const viewRoom = (room) => {
  console.log('查看房间:', room)
}
const editRoom = (room) => {
  editingRoom.value = room
  roomForm.value = { ...room }
  showEditModal.value = true
}
const manageBeds = (room) => {
  ElMessage.info('床位管理功能开发中')
}
const deleteRoom = async (room) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除房间 ${room.number} 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    const res = await deleteRoomAPI(room.id)
    if (res && res.code === 0) {
      ElMessage.success('房间删除成功')
      await fetchRooms()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
const saveRoom = async () => {
  loading.value = true
  try {
    if (showAddModal.value) {
      const res = await addRoomAPI(roomForm.value)
      if (res && res.code === 0) {
        ElMessage.success('房间添加成功')
        await fetchRooms()
        closeModal()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    } else {
      if (!editingRoom.value || !editingRoom.value.id) {
        ElMessage.error('未选择要编辑的房间')
        return
      }
      const res = await updateRoomAPI({
        ...roomForm.value,
        id: editingRoom.value.id
      })
      if (res && res.code === 0) {
        ElMessage.success('房间信息更新成功')
        await fetchRooms()
        closeModal()
      } else {
        ElMessage.error(res.msg || '更新失败')
      }
    }
  } catch (err) {
    ElMessage.error('保存失败')
  } finally {
    loading.value = false
  }
}
const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  editingRoom.value = null
  roomForm.value = {
    roomNumber: '',
    buildingId: '',
    count: 4,
    des: '',
    professionId: '', // 用 professionId
    roomStatus: 0,
    status: 1,
    isMix: 0,
  }
  professionFilter.value = '' // 清空专业筛选
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchRooms()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRooms()
}
const handleSearch = () => {
  currentPage.value = 1
  fetchRooms()
}
// 首次加载
onMounted(async () => {
  await refreshBuildings()
  await fetchRooms()
  // 查询专业列表
  try {
    const res = await queryProfessionAPI()
    // 约定后台res.data为数组，字段有id和name
    if (res && res.code === 0 && res.data) {
      professions.value = res.data || []
    } else {
      professions.value = []
    }
  } catch (e) {
    professions.value = []
  }
})
</script>

<style scoped>
.rooms {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-number {
  font-weight: 600;
  color: #303133;
}

.room-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.building-name {
  color: #409eff;
  font-weight: 500;
}

.bed-count {
  display: flex;
  align-items: center;
  gap: 4px;
}

.count {
  font-weight: 600;
  color: #303133;
}

.label {
  color: #909399;
  font-size: 12px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}


/* 响应式设计 */
@media (max-width: 768px) {
  .rooms {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: stretch;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section .el-input,
  .search-section .el-select {
    width: 100% !important;
  }
}
</style>